package wxy;

import java.util.ArrayDeque;
import java.util.Deque;

public class LeetCode116 {
    class Node {
        public int val;
        public Node left;
        public Node right;
        public Node next;

        public Node() {
        }

        public Node(int _val) {
            val = _val;
        }

        public Node(int _val, Node _left, Node _right, Node _next) {
            val = _val;
            left = _left;
            right = _right;
            next = _next;
        }
    }

    class Solution1 {
        public Node connect(Node root) {
            if (root == null) {
                return null;
            }
            Deque<Node> queue = new ArrayDeque<>();
            queue.offer(root);
            while (!queue.isEmpty()) {
                int n = queue.size();
                for (int i = 0; i < n; i++) {
                    Node curNode = queue.poll();
                    if (i != n - 1) {
                        curNode.next = queue.peek();
                    }
                    if (curNode.left != null) {
                        queue.offer(curNode.left);
                    }
                    if (curNode.right != null) {
                        queue.offer(curNode.right);
                    }
                }
            }
            return root;
        }
    }

    class Solution2 {
        public Node connect(Node root) {
            if (root == null) {
                return null;
            }
            Node leftMost = root;
            while (leftMost.left != null) {
                Node node = leftMost;
                while (node != null) {
                    node.left.next = node.right;
                    if (node.next != null) {
                        node.right.next = node.next.left;
                    }
                    node = node.next;
                }
                leftMost = leftMost.left;
            }

            return root;
        }
    }
}
